import { Component, OnInit } from '@angular/core'
import { TerminalNewBaseClass } from '../baseClass'
import { FormBuilder, Validators } from '@angular/forms'
import { TerminalStoreService } from '../terminal-store.service'
import { TradeAmountMaxValue, positiveReg } from 'app/utils/contraints'
import { I18NService } from '@core'

@Component({
  selector: 'app-terminal-new-trade',
  templateUrl: './trade.component.html',
})
export class TerminalNewTradeComponent extends TerminalNewBaseClass implements OnInit {
  isAmountFixed = false

  errorTips = {}

  constructor(public fb: FormBuilder, public terminalStore: TerminalStoreService, private i18n: I18NService) {
    super(fb, terminalStore)
  }

  ngOnInit(): void {
    this.initErrorTips()
    this.terminalStore.value$.subscribe(terminal => {
      this.terminal = terminal
      this.isAmountFixed = this.terminal.isAmountFixed
    })
    this.initValidateForm()
  }

  initErrorTips(): void {
    this.errorTips = {
      fixedAmt: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.FIXED_AMT_OF_QR_CODE') }),
        min: this.trans('VALIDATION.MIN_VALUE', { value: 0 }),
        max: this.trans('VALIDATION.MAX_VALUE', { value: '10^9' }),
        pattern: this.trans('VALIDATION.PATTERN.INTEGER_ONLY'),
      },
    }
  }

  initValidateForm(): void {
    this.generateValidateForm()
  }

  checkValid(): boolean {
    if (!this.isAmountFixed || this.validateForm.valid) {
      this.pushDataToStore()
      return true
    } else {
      return false
    }
  }

  pushDataToStore(): void {
    if (this.isAmountFixed) {
      const fixedAmt = this.validateForm.value.fixedAmt
      this.terminal.fixedAmt = Number(fixedAmt)
    } else {
      delete this.terminal.fixedAmt
    }
    this.terminal.isAmountFixed = this.isAmountFixed
    this.terminalStore.updateValue(this.terminal)
  }

  switchAmountFixed(isAmountFixed: boolean): void {
    this.isAmountFixed = isAmountFixed
    isAmountFixed ? this.generateValidateForm() : this.resetValidateForm()
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }

  private generateValidateForm(): void {
    const { fixedAmt } = this.terminal
    this.validateForm = this.fb.group({
      fixedAmt: [
        fixedAmt,
        [Validators.required, Validators.min(0), Validators.max(TradeAmountMaxValue), Validators.pattern(positiveReg)],
      ],
    })
  }

  private resetValidateForm(): void {
    this.validateForm = this.fb.group({})
  }
}
